import logging
import random
import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, GenericAPIView
from celery_tasks.sms.tasks import send_sms
from .serializers import *
from .utils import generate_access_token_openid, check_access_token_openid

logger = logging.getLogger('django')


class SMSCodeView(APIView):

    def get(self, request, mobile):


        conn = get_redis_connection('verify_code')
        # 判断60秒之内是否发送过短信
        flag = conn.get("sms_flag_%s"%mobile)
        if flag:
           return Response({'success': 0, 'message': '发送频繁'})

        # 2、调用云通讯发送短信
        # 2.1 生成一个随机的短信验证码(6位数)
        sms_code = "%06d" % random.randint(0, 999999)
        # 2.2 短信验证码存储进redis，设计key：sms_{手机号}
        p = conn.pipeline() # 获取一个管道对象
        try:
            p.setex("sms_%s"%mobile, 300, sms_code)
            # 添加标志位
            p.setex("sms_flag_%s"%mobile, 60, '-1')
            p.execute() # 通过管道批量执行redis指令
        except Exception as e:
            logger.info(e)
            return Response({'success': 0, 'message': '发送失败'})

        # 2.3 调用云通讯发送短信
        # send_sms.delay(mobile, sms_code)
        send_sms(mobile, sms_code)

        # 3、构建响应返回
        return Response({'success': 1, 'message': 'ok', 'sms_code': sms_code})


class CreateUserView(CreateAPIView):
    serializer_class = UserSeializers

    def post(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        data = ser.validated_data
        user = User.objects.create_user(**data)
        payload = {"user_id": user.id, "username": user.username}
        token = jwt_encode_handler(payload)
        return Response({
            'code': 0,
            'token': token,
            'id': user.id,
            'mobile': user.mobile,
            'avatar': user.avatar,
            'username': user.username
        })


class WeiBoUrlView(APIView):

    def get(self, request):
        URL_WB = 'https://api.weibo.com/oauth2/authorize?client_id='
        url = URL_WB + settings.APPID + '&redirect_uri=' + settings.REDIRECT_URL + '&response_type=code'
        return Response({'code':0, 'login_url': url})


# 第三方微博登录
class WeiboOauthView(APIView):

    def get(self, request):
        url_token = 'https://api.weibo.com/oauth2/access_token'
        code = request.query_params.get('code')
        post_data = {
            'client_id': settings.APPID,
            'client_secret': settings.APPSECRET,
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': settings.REDIRECT_URL
        }
        res = requests.post(url_token, data=post_data).text
        res = eval(res)
        token = res.get('access_token')
        # 通过token去数据库查找到是否绑定登录用户
        try:
            wu = OAuthWeixinUser.objects.get(openid=token)
        except OAuthWeixinUser.DoesNotExist:
            # 用户未绑定
            access_token = generate_access_token_openid(token)
            return Response({'code':300, 'errmsg':'未绑定', 'access_token': access_token})
        else:
            # 用户已绑定
            user =wu.user
            payload = {"user_id": user.id, "username": user.username}
            token = jwt_encode_handler(payload)
            return Response({
                'code': 0,
                'token': token,
                'id': user.id,
                'mobile': user.mobile,
                'avatar': user.avatar,
                'username': user.username
            })

    def post(self, request):
        actoken = request.data.get('access_token')
        openid = check_access_token_openid(actoken)
        if not openid:
            return Response({'code': 400, 'errmsg': '绑定失败', 'status':'400'})
        data = request.data
        data['openid'] = openid
        mobile = data.get('mobile')
        password = data.get('password')
        conn = get_redis_connection('verify_code')
        # code = conn.get("sms_%s" % mobile).decode()
        # if not code:
        #     return Response({'code': 400, 'errmsg': '验证码错误'})
        # conn.delete("sms_%s" % mobile)
        # if code != str(attrs.get('sms_code')):
        #     return Response({'code': 400, 'errmsg': '验证码错误'})
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        if not user.check_password(password):
            return Response({'code': 400, 'errmsg': '密码错误'})
        OAuthWeixinUser.objects.create(openid=openid, user=user)
        payload = {"user_id": user.id, "username": user.username}
        token = jwt_encode_handler(payload)
        return Response({
            'code': 0,
            'token': token,
            'id': user.id,
            'mobile': user.mobile,
            'avatar': user.avatar,
            'username': user.username
        })


# 图片上传得到路径
from fdfs_client.client import Fdfs_client
from django.conf import settings
from ten.utils.fastdfs.fastdfs_storage import FastDFSStorage
class UploadAvatarView(APIView):
    def post(self, request):
        # fdfs = Fdfs_client('ten/utils/fastdfs/client.conf')
        # ava = request.FILES.get('img').file.read()
        # res = fdfs.upload_by_buffer(ava)
        # if res['Status'] != 'Upload successed.':
        #     raise serializers.ValidationError("上传失败")

        ava = request.FILES.get('img').file
        imgurl = FastDFSStorage().save(name='', content=ava)
        imgurl = FastDFSStorage().url(imgurl)
        return Response({'imgurl': imgurl})


from django.views import View
from django.http import HttpResponseRedirect
class UploadCommonView(View):
    def post(self, request):
        # fdfs = Fdfs_client('ten/utils/fastdfs/client.conf')
        # ava = request.FILES.get('upload').read()
        # res = fdfs.upload_by_buffer(ava)
        # if res['Status'] != 'Upload successed.':
        #     raise serializers.ValidationError("上传失败")
        # imgurl = res['Remote file_id']
        # url = "http://127.0.0.1:8080/upload_success.html?image_url=" + settings.FDFS_URL + imgurl + "&CKEditorFuncNum=1"
        # return HttpResponseRedirect(url)

        ava = request.FILES.get('upload')
        imgurl = FastDFSStorage().save(name='', content=ava)
        url = "http://www.1024.site:8080/upload_success.html?image_url=" + settings.FDFS_URL + imgurl + "&CKEditorFuncNum=1"
        return HttpResponseRedirect(url)










